<?php

namespace App\Kuafu\Shop\Controller\Pos;

use App\Exceptions\BaseException;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\Shop\Validate\ShopValidate;
use App\Kuafu\User\Exceptions\UserException;
use App\Kuafu\User\Service\AuthService;
use App\Support\MQTT;
use Doctrine\DBAL\Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Psr\SimpleCache\InvalidArgumentException;

class ShopController extends BaseController
{
    /**
     * 获取 MQTT 服务账号登录信息
     * @return JsonResponse
     * @throws UserException
     */
    public function getMQTTAccount(Request $request): JsonResponse
    {
        $userId = AuthService::getUserId();
        $shopId = $request->header("shopId");
        $result = [
            "account" => MQTT::getAccount($userId, $shopId),
            'shop'    => MQTT::getAccountByConnectType($userId, $shopId, MQTT::MQTT_CLIENT_CONNECT_SHOP),
        ];

        return $this->success($result);
    }

    /**
     * 获取店铺信息
     * @param Request $request
     * @return JsonResponse
     */
    public function getShopInfo(Request $request)
    {
        if (empty($request->shopId)) {
            $this->fail(ShopCodeEnum::ERR_400000);
        }
        $info = ShopService::getShopInfoShow($request->shopId);
        return $this->success($info);
    }

    /**
     * POS 设备绑定
     *
     * @throws GuzzleException
     * @throws BaseException
     * @throws InvalidArgumentException
     * @throws Exception
     * @throws UserException
     * @throws ShopException
     */
    public function bandPosSerialNumber(Request $request): JsonResponse
    {
        $valid = ShopValidate::bandSerialNumber($request);
        if ($valid) {
            return $this->fail(ShopCodeEnum::ERR_BANS_INPUT_SERIAL_NUMBER,
                ShopCodeEnum::CODE_TEXT[ShopCodeEnum::ERR_BANS_INPUT_SERIAL_NUMBER]);
        }
        $shopId   = $request->shopId;
        $shopInfo = ShopService::getShopInfo($shopId);
        if ($shopInfo['serialNumber']) {
            return $this->fail(ShopCodeEnum::ERR_BANS_HAS_SERIAL_NUMBER,
                ShopCodeEnum::CODE_TEXT[ShopCodeEnum::ERR_BANS_HAS_SERIAL_NUMBER]);
        }
        $serialNumber = $request->serialNumber ?? '';
        ShopService::bandPosSerialNumber($shopId, $serialNumber);
        return $this->success();
    }

}
